package com.xiaogao.common.utils.token;

import com.xiaogao.common.entity.TokenEntity;
import com.xiaogao.common.exception.BusinessException;
import com.xiaogao.common.utils.UUIDUtils;
import io.jsonwebtoken.*;
import lombok.extern.slf4j.Slf4j;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Slf4j
public class JwtUtils {
    private static final String SECRET_KEY = "your_secret_key";

    public static String create(TokenEntity tokenEntity) {
        // 设置JWT的过期时间
        long nowMillis = System.currentTimeMillis();
        Date now = new Date(nowMillis);

        // 创建JWT的payload部分
        Map<String, Object> claims = new HashMap<>();
        claims.put("uuid", UUIDUtils.uuid());
        claims.put("username", tokenEntity.getUsername());
        claims.put("realName", tokenEntity.getRealName());
        claims.put("userId", tokenEntity.getUserId());
        claims.put("deptId", tokenEntity.getDeptId());
        claims.put("dataScopes", tokenEntity.getDataScopes());

        // 生成JWT
        return Jwts.builder()
                .setClaims(claims)
                .setIssuedAt(now) // 签发时间
                .signWith(SignatureAlgorithm.HS256, SECRET_KEY) // 使用HS256算法和密钥进行签名
                .compact();
    }

    /**
     * 解析JWT token并获取claims
     *
     * @param token 要解析的JWT token
     * @return token中的claims
     */
    public static Claims parse(String token) {
        // 使用相同的密钥和签名算法来解析JWT
        try {
            return Jwts.parser()
                    .setSigningKey(SECRET_KEY) // 设置签名密钥
                    .parseClaimsJws(token) // 解析JWT
                    .getBody(); // 获取claims
        } catch (ExpiredJwtException | UnsupportedJwtException | MalformedJwtException | SignatureException |
                 IllegalArgumentException e) {
            log.error("token非法！", e);
            throw new BusinessException(2000, "token非法！");
        }
    }

    public static boolean isAdmin(String username) {
        return "admin".equals(username);
    }


    public static String userId(String token) {
        Claims claims = parse(token);
        return String.valueOf(claims.get("userId"));
    }

    public static String username(String token) {
        Claims claims = parse(token);
        return String.valueOf(claims.get("username"));
    }
}
